package com.caishi.lkx.user.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.user.ienum.status.UserGroupStatus;
import com.caishi.lkx.user.ienum.type.UserAccountType;
import com.caishi.lkx.user.model.IUserModel;
import com.caishi.lkx.user.model.LoginInfoModel;
import com.caishi.lkx.user.model.UserModel;
import com.caishi.lkx.user.model.re.UserGroupReModel;
import com.caishi.lkx.user.service.IGroupService;
import com.caishi.lkx.user.service.ILoginInfoService;
import com.caishi.lkx.user.service.IUserGroupReService;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.Wrappers;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;


@Tag(name = "用户-机构绑定")
@RestController
@RequestMapping("/user/group/re")
public class UserGroupReApi extends AdminBaseApi<IUserGroupReService, UserGroupReModel, Long> {
    @Resource
    private IUserGroupReService userGroupReService;
    @Resource
    private IGroupService groupService;
    @Resource
    private IUserService<UserModel> userService;
    @Resource
    private ILoginInfoService loginInfoService;

    @Override
    public IUserGroupReService loadService() {
        return userGroupReService;
    }


    @PostMapping("/change")
    @Roles({Role.onlyLogin})
    @Operation(summary = "审核用户绑定状态")
    public Boolean changeStatus(@RequestParam List<Long> ids, @RequestParam UserGroupStatus status) {
        return userGroupReService.changeStatus(ids, status);
    }

    @Override
    protected List<UserGroupReModel> listCover(List<UserGroupReModel> result, JSONObject otherParam) {
        return result.parallelStream().peek(r -> {
            LoginInfoModel infoModel = loginInfoService.selectUserLoginInfo(r.getUserId(), UserAccountType.username);
            if (infoModel != null) {
                r.setUserName(infoModel.getAccount());
            }
            IUserModel<UserModel> userDetail = userService.getUserDetail(r.getUserId());
            r.setName(userDetail.getName());
            r.setHeader(userDetail.getHeader());
            r.setGroupName(groupService.queryName(r.getGroupId()));
        }).collect(Collectors.toList());

    }

    @Override
    @GetMapping("/page")
    public IPage<UserGroupReModel> page(@ModelAttribute Page<UserGroupReModel> page, @ModelAttribute UserGroupReModel model, @NotNull JSONObject otherParam) {
        List<String> userIds = new ArrayList<>();
        if (StrUtil.isNotBlank(model.getUserName())) {
            List<String> userIds2 = loginInfoService.selectList(Wrappers.<LoginInfoModel>lambdaQuery().select(LoginInfoModel::getUserId)
                    .eq(LoginInfoModel::getLoginType, UserAccountType.username)
                    .like(LoginInfoModel::getAccount, model.getUserName())).stream().map(LoginInfoModel::getUserId).collect(Collectors.toList());
            if (CollUtil.isEmpty(userIds2)) {
                return page;
            }
            userIds.addAll(userIds2);
        }
        if (StrUtil.isNotBlank(model.getName())) {
            List<String> userIds3 = userService.getIdsByNameAndIds(model.getName(), null);
            if (CollUtil.isEmpty(userIds3)) {
                return page;
            }
            if (CollUtil.isNotEmpty(userIds)) {
                userIds.retainAll(userIds3);
                if (CollUtil.isEmpty(userIds)) {
                    return page;
                }
            } else {
                userIds.addAll(userIds3);
            }

        }
        IPage<UserGroupReModel> data = loadService().page(loadService().pageProcessing(page), baseWrapper(model, otherParam)
                .in(CollUtil.isNotEmpty(userIds), UserGroupReModel::getUserId, userIds));
        data.setRecords(listCover(data.getRecords(), otherParam));
        return data;
    }

    // ****************************** 前台pc接口 *******************************
    // ****************************** 前台pc接口 *******************************
    // ****************************** 前台pc接口 *******************************

    @PostMapping("/bind")
    @Roles({Role.onlyLogin})
    @Operation(summary = "用户绑定机构")
    @Parameters({
            @Parameter(name = "要绑定的机构id", description = "groupId"),
            @Parameter(name = "经度", description = "longitude"),
            @Parameter(name = "纬度度", description = "latitude"),
    })
    public Boolean bind(@RequestParam Long groupId, BigDecimal longitude, BigDecimal latitude) throws InterruptedException, TimeoutException {
        return userGroupReService.bind(groupId, userContext.currentUserId(), userContext.currentIp(), longitude, latitude);
    }

    @PostMapping("/unBind")
    @Roles({Role.onlyLogin})
    @Operation(summary = "用户解绑机构")
    public Boolean unBind() throws InterruptedException, TimeoutException {
        return userGroupReService.unBind(userContext.currentUserId());
    }

    @PostMapping("/updateExpireDate")
    @Roles({Role.onlyLogin})
    @Operation(summary = "用户延长过期时间")
    @Parameters({
            @Parameter(name = "新的过期时间(优先)", description = "newDate"),
            @Parameter(name = "新的过期天数(天)", description = "days"),
    })
    public Boolean updateExpireDate(LocalDate newDate, Integer days) {
        return userGroupReService.updateExpireDate(userContext.currentUserId(), newDate, days);
    }
}
